package com.primaryedu.ui.app.classadjust;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.primaryedu.R;
import com.primaryedu.data.Contants;
import com.primaryedu.data.GlobalData;
import com.primaryedu.dialog.ListDialog;
import com.primaryedu.dialog.ListDialog.OnItemListener;
import com.primaryedu.ui.BaseActivity;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;

public class ClassAdjustDetailsActivity extends BaseActivity implements OnClickListener, OnItemListener {
    private TextView text_choose_date, text_choose_date_two;
    private final static int DATE_DIALOG = 0;
    private Calendar calendar = null;
    Dialog dateDialog = null;
    private String timeOne = "";
    private String timeOneStr = "";
    private String dateFlag = "0";

    private EditText edit_name, edit_name_two;
    private EditText edit_grade, edit_grade_two;
    private TextView text_pitch, text_pitch_two;

    private TextView text_subject, text_subject_two;

    ListDialog listDialog;
    private List<String> subjectStrs = new ArrayList<>();
    private String flagStr = "1";

    ListDialog pitchDialog;
    private List<String> pitchStrs = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_class_adjust_details);

        init();

    }

    private void init() {
        ((TextView) findViewById(R.id.title)).setText("申请调课");
        findViewById(R.id.back).setOnClickListener(this);
        findViewById(R.id.next).setOnClickListener(this);

        text_choose_date = (TextView) this.findViewById(R.id.text_choose_date);
        text_choose_date.setOnClickListener(this);
        text_choose_date_two = (TextView) this.findViewById(R.id.text_choose_date_two);
        text_choose_date_two.setOnClickListener(this);

        edit_name = (EditText) this.findViewById(R.id.edit_name);
        edit_name_two = (EditText) this.findViewById(R.id.edit_name_two);
        edit_grade = (EditText) this.findViewById(R.id.edit_grade);
        edit_grade_two = (EditText) this.findViewById(R.id.edit_grade_two);
        text_subject = (TextView) this.findViewById(R.id.text_subject);
        text_subject.setOnClickListener(this);
        text_subject_two = (TextView) this.findViewById(R.id.text_subject_two);
        text_subject_two.setOnClickListener(this);
        text_pitch = (TextView) this.findViewById(R.id.text_pitch);
        text_pitch.setOnClickListener(this);
        text_pitch_two = (TextView) this.findViewById(R.id.text_pitch_two);
        text_pitch_two.setOnClickListener(this);

        edit_name.setText(GlobalData.getUsername(getApplicationContext()));

        listDialog = new ListDialog(ClassAdjustDetailsActivity.this);
        subjectStrs.clear();
        subjectStrs.add("语文");
        subjectStrs.add("数学");
        subjectStrs.add("外语");
        subjectStrs.add("音乐");
        subjectStrs.add("体育");
        subjectStrs.add("美术");
        subjectStrs.add("综合");
        subjectStrs.add("品德");
        subjectStrs.add("科学");
        subjectStrs.add("信息");
        subjectStrs.add("队会");
        subjectStrs.add("其他");
        listDialog.setList(subjectStrs);
        listDialog.setOnItemListener(this);

        pitchDialog = new ListDialog(ClassAdjustDetailsActivity.this);
        pitchStrs.clear();
        pitchStrs.add("早");
        pitchStrs.add("中");
        pitchStrs.add("困");
        pitchStrs.add("1");
        pitchStrs.add("2");
        pitchStrs.add("3");
        pitchStrs.add("4");
        pitchStrs.add("5");
        pitchStrs.add("6");
        pitchStrs.add("7");
        pitchDialog.setList(pitchStrs);
        pitchDialog.setOnItemListener(this);

    }

    @Override
    protected int BindLayout() {
        return R.layout.activity_class_adjust_details;
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initData() {

    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.back:
                finish();
                break;

            case R.id.text_choose_date:
                dateFlag = "1";
                showDialog(DATE_DIALOG);
                break;

            case R.id.text_choose_date_two:
                dateFlag = "2";
                showDialog(DATE_DIALOG);
                break;

            case R.id.next:
                next();
                break;

            // 学科 一
            case R.id.text_subject:
                flagStr = "1";
                listDialog.show();
                break;

            // 学科二
            case R.id.text_subject_two:
                flagStr = "2";
                listDialog.show();
                break;

            // 节数一
            case R.id.text_pitch:
                flagStr = "3";
                pitchDialog.show();
                break;

            // 节数二
            case R.id.text_pitch_two:
                flagStr = "4";
                pitchDialog.show();
                break;

            default:
                break;
        }
    }

    private void next() {
        StringBuilder builder = new StringBuilder();
//		builder.append("申请信息\n"+edit_name.getText().toString()).append(",") ;
//		builder.append(edit_grade.getText().toString()).append(",") ;
//		builder.append(text_subject.getText().toString()).append(",") ;
//		builder.append("第"+text_pitch.getText().toString()).append("节");
//		builder.append(text_choose_date.getText().toString());
        builder.append("调课信息\n").append("教师姓名:" + edit_name_two.getText()).append(",");
        builder.append("班级:" + edit_grade_two.getText().toString()).append(",");
        builder.append("科目:" + text_subject.getText().toString()).append(",");
        builder.append("第" + text_pitch_two.getText().toString()).append("节");
        builder.append("时间:" + text_choose_date_two.getText().toString());

        System.out.println("builder===" + builder.toString());

        if (TextUtils.isEmpty(edit_name.getText().toString())) {
            showToast("请输入申请教师姓名");
            return;
        }

        if (TextUtils.isEmpty(edit_grade.getText().toString())) {
            showToast("请输入申请教师所在班级");
            return;
        }

        if (TextUtils.isEmpty(edit_grade.getText().toString())) {
            showToast("请输入申请调课科目");
            return;
        }

        if (TextUtils.isEmpty(edit_grade.getText().toString())) {
            showToast("请输入要调第几节课");
            return;
        }

        if (TextUtils.isEmpty(text_choose_date.getText().toString())) {
            showToast("请输入要调课时间");
            return;
        }

        requestData(builder.toString());
    }

    private void requestData(final String remarks) {
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Contants.courseSave,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        System.out.println("courseSave==" + response);

                        try {
                            JSONObject json = new JSONObject(response);
                            int result = json.getInt("result");

                            if (result == 1) {
                                showToast("提交成功！");
                                finish();
//						    	  String data = json.getString("data") ;
//						    	  JSONObject listObj = new JSONObject(data) ;
//						    	  String listStr = listObj.getString("list") ;
//						    	  
//						    	  list = new Gson().fromJson(listStr,
//					    					new TypeToken<List<ClassBean>>() {
//					    					}.getType());
//						    	  tempList.addAll(list) ;
//						    	  handler.sendEmptyMessage(1001) ;
//						    	  System.out.println("getNotice=="+list);
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                //在这里设置需要post的参数
                Map<String, String> map = new HashMap<String, String>();
                map.put("classname", edit_grade.getText().toString());   // 班级
                map.put("week", text_choose_date.getText().toString());  // 日期
                map.put("lesson", text_pitch.getText().toString());  // 第几节
                map.put("subject", text_subject.getText().toString());  // 科目
                map.put("teacher", edit_name.getText().toString());  // 教师姓名
                map.put("remarks", remarks);  // 备注
                map.put("createBy.id", GlobalData.getUserId(getApplicationContext()));
                return map;
            }
        };
        requestQueue.add(stringRequest);
    }


    /**
     * 创建日期及时间选择对话框
     */
    @Override
    protected Dialog onCreateDialog(int id) {
//        Dialog dialog = null;
        switch (id) {
            case DATE_DIALOG:
                calendar = Calendar.getInstance();
                dateDialog = new DatePickerDialog(
                        this, R.style.time_dialog,
                        new DatePickerDialog.OnDateSetListener() {
                            @SuppressWarnings("deprecation")
                            public void onDateSet(DatePicker dp, int year, int month, int dayOfMonth) {

                                // 时间格式
                                if (month < 9) {

                                    if (dayOfMonth <= 9) {
                                        timeOne = year + "-0" + (month + 1) + "-0" + dayOfMonth;
                                        timeOneStr = (month + 1) + "-0" + dayOfMonth;
                                    } else {
                                        timeOne = year + "-0" + (month + 1) + "-" + dayOfMonth;
                                        timeOneStr = (month + 1) + "-" + dayOfMonth;
                                    }

                                } else {

                                    if (dayOfMonth <= 9) {
                                        timeOne = year + "-" + (month + 1) + "-0" + dayOfMonth;
                                        timeOneStr = (month + 1) + "-0" + dayOfMonth;
                                    } else {
                                        timeOne = year + "-" + (month + 1) + "-" + dayOfMonth;
                                        timeOneStr = (month + 1) + "-" + dayOfMonth;
                                    }
                                }

                                if (dateFlag.equals("1")) {
                                    text_choose_date.setText(timeOne + "日 " + dateToWeek(timeOne));
                                } else if (dateFlag.equals("2")) {
                                    text_choose_date_two.setText(timeOne + "日 " + dateToWeek(timeOne));
                                }

                            }
                        },
                        calendar.get(Calendar.YEAR), // 传入年份
                        calendar.get(Calendar.MONTH), // 传入月份
                        calendar.get(Calendar.DAY_OF_MONTH) // 传入天数
                );
                dateDialog.setCanceledOnTouchOutside(false);
                break;
        }

        return dateDialog;
    }


    /**
     * 日期转星期
     *
     * @param datetime
     * @return
     */
    public static String[] WEEK = {"星期天","星期一","星期二","星期三","星期四","星期五","星期六"};
    public static final int WEEKDAYS = 7;

    public static String DateToWeek(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int dayIndex = calendar.get(Calendar.DAY_OF_WEEK);
        if (dayIndex < 1 || dayIndex > WEEKDAYS) {
            return null;
        }

        return WEEK[dayIndex - 1];
    }


    public static String dateToWeek(String datetime) {
        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
        String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
        Calendar cal = Calendar.getInstance(); // 获得一个日历
        Date datet = null;
        try {
            datet = f.parse(datetime);
            cal.setTime(datet);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        int dayIndex = cal.get(Calendar.DAY_OF_WEEK);
        if (dayIndex < 1 || dayIndex > WEEKDAYS) {
            return null;
        }
        return WEEK[dayIndex - 1];
//        return WEEK[dayIndex - 1];
//        int w = cal.get(Calendar.DAY_OF_WEEK) - 1; // 指示一个星期中的某天。
//        if (w < 0)
//            w = 0;
//        return weekDays[w];
    }

    @Override
    public void onChoose(String content) {
        if (flagStr.equals("1")) {
            text_subject.setText(content);
        } else if (flagStr.equals("2")) {
            text_subject_two.setText(content);
        } else if (flagStr.equals("3")) {
            text_pitch.setText(content);
        } else if (flagStr.equals("4")) {
            text_pitch_two.setText(content);
        }


    }


}
